﻿using UnityEngine;

public class RectSize : NodeSize
{
    public RectTransform rectTransform;
    public Vector2 min;
    public Vector2 max;

    protected override void OnRefresh(float rw, float rh, float w, float h, float s)
    {
        SetRatio(GetRatio(rw, rh, w, h));
    }

    private void SetRatio(float value)
    {
        var size = Vector2.Lerp(min, max, value);
        SetWidth(size.x);
        SetHeight(size.y);
    }

    protected float GetRatio(float rw, float rh, float w, float h)
    {
        var v1 = rw / rh;
        var v2 = rh / rw;
        var v = w / h;
        if (v < v1) return 0;
        if (v > v2) return 1;
        return (v - v1) / (v2 - v1);
    }

    protected void SetWidth(float w)
    {
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, w);
    }

    protected void SetHeight(float h)
    {
        rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, h);
    }
}